import random

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from user import models, userser
from rest_framework.views import APIView

from utils import duanxin,myredis
from utils.tooljwt import ToolJwt, tool
# from .authentication import JWTAuthentication
from utils.authentications import UserJWTAuthentication


# Create your views here.

class UsersRegister(APIView):
    def post(self, request):
        ser = userser.UsersSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"mes": "ok", "data": ser.data, "code": status.HTTP_201_CREATED})
        else:
            return Response({"mes": "error", "data": ser.errors, "code": status.HTTP_400_BAD_REQUEST})


class UsersLogin(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")
        data = models.Users.objects.filter(username=username).first()
        if data:
            if data.password == password:
                token = tool.get_token({"id": data.id, "username": data.username})
                return Response({"mes": "ok", "data": {'id': data.id, 'username': data.username, "token": token},
                                 "code": status.HTTP_200_OK})
            else:
                return Response({"mes": "error", "data": "密码错误", "code": status.HTTP_400_BAD_REQUEST})
        else:
            return Response({"mes": "error", "data": "用户不存在", "code": status.HTTP_400_BAD_REQUEST})


# class Test(APIView):
#     authentication_classes = (JWTAuthentication,)
#
#     def get(self, request):
#         return Response({"mes": "ok", "data": "ok", "code": status.HTTP_200_OK})


class UsersCenter(APIView):
    authentication_classes = (UserJWTAuthentication,)

    def get(self, request):
        return Response({"mes": "我是会员中心"})


class SendCode(APIView):
    def post(self, request):
       phone = request.data.get("phone")
       code = random.randint(1000, 9999)
       duanxin.send_message(phone, code,2)
       if res['statusCode'] == '000000':
           myredis.MyRedis.set_time_str(phone, code, 60 * 5)